#include "file.h"
#include "gcode.h"
#include <string.h>
#include "display.h"
#include "keyboard.h"
#include "delay.h"
#include "rs232_interface.h"


int fileListSz = 0, currentFile = 0, firstFileInWin = 0;
FileListST fileList[MAX_FILE_LIST_SZ];

char loadedFileName[MAX_FILE_NAME_SZ];
const char path[] = "0:/";


/***************************************************
 *  初始化文件系统
 ***************************************************/
void FileInit(void)
{
    FRESULT fres = f_mount(&fs, FS_VOLUME_SD, 1);   /* Mount a logical drive */
    if (fres != FR_OK)
    {
        showCriticalStatus(
            " Mount SD error [code:%d]\n"
            " SD card is not availiable\n"
            " Only RESET possible at now", fres);
        DBG_FATAL("Mount SD error");
        WAIT_KEY_C();
    }
}


/***************************************************
 *  Read file list
 ***************************************************/
void readFileList(void)
{
    FRESULT fres;
    FILINFO finfo;
    DIR dirs;
    //    static char cLongFileName[FF_MAX_SS + 1];

    DBG_TRACE("Open SD dir.. ");
    if ((fres = f_opendir(&dirs, (const TCHAR*)path)) != FR_OK)
    {
        win_showMsgWin();
        scr_gotoxy(2, 0);
        showCriticalStatus(" f_opendir()\n  error [code:%d]\n  Only RESET possible at now", fres);
        WAIT_KEY_C();
        return;
    }

    // scr_puts("\nRead file list");
//    finfo.fname = cLongFileName;
//    finfo.fsize = sizeof(cLongFileName);
    for (fileListSz = 0; f_readdir(&dirs, &finfo) == FR_OK && fileListSz < MAX_FILE_LIST_SZ;)
    {
        DBG_DEBUG("File%d:%s", fileListSz, finfo.fname);
        scr_gotoxy(0, 3);
        // scr_printf("files:[%d]", fileListSz);
        if (!finfo.fname[0])
            break;
        if (finfo.fname[0] == '.')
            continue;
        if (!(finfo.fattrib & AM_DIR) && strcmp(CONF_FILE_NAME, finfo.fname) != 0)
        {
            strncpy(fileList[fileListSz].f_name, finfo.fname, MAX_FILE_NAME_SZ);
            fileList[fileListSz].f_size = finfo.fsize;
            fileList[fileListSz++].f_type = 1;

        }
    }
    if (loadedFileName[0] != 0)
    {
        // set last loaded file as selected file scr_printf("\nselect:'%s'..", loadedFileName);
        for (int i = 0; i < fileListSz; i++)
        {
            if (!strcmp(fileList[i].f_name, &loadedFileName[0]))
            {
                loadedFileName[0] = 0; // reset for next dir reload
                currentFile = i;
                if (currentFile < FILE_LIST_ROWS)
                {
                    firstFileInWin = 0;
                }
                else if ((fileListSz - currentFile) < FILE_LIST_ROWS)
                {
                    firstFileInWin = fileListSz - FILE_LIST_ROWS;
                }
                else
                {
                    firstFileInWin = currentFile;
                }
                break;
            }
        }
    }
}

/***************************************************
 *  Draw file list
 ***************************************************/
void drawFileList(void)
{
    int8_t pos = 0;
    KEY_ENUM c;
    win_showMenu(0, 50, 40, 13, "Select File");

    do
    {
        if (c == KEY_D_DOWN) pos = pos <= 0 ? (fileListSz - 1) : pos - 1;
        if (c == KEY_U_DOWN) pos = pos >= (fileListSz - 1) ? 0 : pos + 1;
        scr_gotoxy(0, 0);

        for (int i = 0; i < fileListSz; i++)
        {
            if (i == pos)
                scr_fontColorInvers();
            else
                scr_fontColorNormal();
            scr_printf("-> %s", fileList[i].f_name);
            scr_clrEndl();
            scr_gotoxy(20, i);
            scr_printf(" |%5d KB\n", fileList[i].f_size / 1024);
        }
        c = kbd_GetKey();
        delay_ms(10);
    } while (c != KEY_R_DOWN && c != KEY_C_DOWN);
    if (c == KEY_C_DOWN)
    {
        currentFile = INVALID_VALUE_INT;
    }
    else
    {
        currentFile = pos;
    }
}

/***************************************************
 *  获取文件行数
 ***************************************************/
uint32_t GetFileLineNum(char* file)
{
    char ff[100] = { 0 };
    uint32_t linenum = 0;
    FRESULT  res = f_open(&fid, file, FA_READ);
    while (f_gets(ff, 100, &fid) == NULL)
    {
        linenum++;
    }
    return linenum;
}


